package com.ygqh.baby.service.impl;

import com.ygqh.baby.ao.*;
import com.ygqh.baby.mapper.YgGroupBuyingMapper;
import com.ygqh.baby.model.YgGroupBuyModel;
import com.ygqh.baby.model.YgGroupOrderRemindModel;
import com.ygqh.baby.model.YgProductGroupModel;
import com.ygqh.baby.model.YgPtSkuInfo;
import com.ygqh.baby.po.YgGroup;
import com.ygqh.baby.po.YgGroupBuying;
import com.ygqh.baby.po.YgGroupBuyingExample;
import com.ygqh.baby.redis.RedisDao;
import com.ygqh.baby.service.YgGroupBuyingService;
import com.ygqh.baby.service.YgGroupService;
import com.ygqh.baby.utils.DateConvertUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class YgGroupBuyingServiceImpl implements YgGroupBuyingService {

    @Autowired
    private YgGroupBuyingMapper ygGroupBuyingMapper;
    @Autowired
    private YgGroupService ygGroupService;
    @Autowired
    private RedisDao redisDao;

    @Override
    public List<YgGroupBuying> find() {
        YgGroupBuyingExample example = new YgGroupBuyingExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        return ygGroupBuyingMapper.selectByExample(example);
    }

    @Override
    public int findCount() {
        YgGroupBuyingExample example = new YgGroupBuyingExample();
        example.createCriteria().andStatusEqualTo(DataStatus.Valid.name());
        return ygGroupBuyingMapper.countByExample(example);
    }

    @Override
    public YgGroupBuying findById(Long id) {
        return ygGroupBuyingMapper.selectByPrimaryKey(id);
    }

    @Override
    public int save(YgGroupBuying ygGroupBuying) {
        return ygGroupBuyingMapper.insertSelective(ygGroupBuying);
    }

    @Override
    public int update(YgGroupBuying ygGroupBuying) {
        return ygGroupBuyingMapper.updateByPrimaryKeySelective(ygGroupBuying);
    }

    @Override
    public ResultSet<YgGroupBuying> search(QueryInfo queryInfo, String q) {
        List<YgGroupBuying> list = ygGroupBuyingMapper.selectSuper(queryInfo, q);
        int count = ygGroupBuyingMapper.countSuper(q);
        ResultSet<YgGroupBuying> resultSet = new ResultSet<YgGroupBuying>(count, list);
        return resultSet;
    }

    @Override
    public int deleteSoft(Long[] ids) {
        Assert.notEmpty(ids);
        YgGroupBuyingExample example = new YgGroupBuyingExample();
        example.createCriteria().andIdIn(Arrays.asList(ids));
        YgGroupBuying record = new YgGroupBuying();
        record.setStatus(DataStatus.Delete);

        return ygGroupBuyingMapper.updateByExampleSelective(record, example);
    }

    @Override
    public int deleteSoft(Long id) {
        return this.deleteSoft(new Long[]{id});
    }

    @Override
    public int saveOrUpdate(YgGroupBuying ygGroupBuying) {
        int r = 0;
        if (ygGroupBuying.getId() != null) {
            r = this.update(ygGroupBuying);
        } else {
            r = this.save(ygGroupBuying);
        }
        return r;
    }

    @Override
    public List<YgGroupBuyModel> findGroupBuyByGroupId(QueryInfo queryInfo, Long groupId) {
        return ygGroupBuyingMapper.selectGroupBuyByGroupId(queryInfo, groupId);
    }

    @Override
    public YgGroupBuying addGroupBuyIng(Long groupId, Long userId, Long amount) {
        /**
         * 这个方法里不要设置 completeStatus
         */

        YgGroup group = ygGroupService.findById(groupId);
        YgGroupBuying buy = new YgGroupBuying();
        buy.setGroupId(groupId);
        buy.setStatus(DataStatus.Delete);
        buy.setFinishAmount(amount);
        buy.setUserId(userId);
        buy.setCreateTime(new Date());
        buy.setIsReal(group.getIsReal());
        buy.setGroupAmount(group.getGroupAmount());
        buy.setCompleteTime(DateConvertUtils.addMinute(buy.getCreateTime(), group.getGroupDate() * 60));
        this.save(buy);
        return buy;
    }

    @Override
    public YgGroupBuyModel findGroupBuyById(Long groupBuyId) {
        return ygGroupBuyingMapper.selectGroupBuyById(groupBuyId);
    }

    @Override
    public YgProductGroupModel findProductInfoWithGroup(Long productId) {
        return ygGroupBuyingMapper.selectProductInfoWithGroup(productId);
    }

    @Override
    public List<YgProductGroupModel> findOtherGroupProduct(QueryInfo queryInfo, Long productId) {
        return ygGroupBuyingMapper.selectOtherGroupProduct(queryInfo, productId);
    }

    @Override
    public List<YgGroupBuyModel> findAllGroupBuy(QueryInfo queryInfo) {
        return ygGroupBuyingMapper.selectAllGroupBuy(queryInfo);
    }

    @Override
    public int updateGroupBuyStatusByPaySuccess(Long groupBuyId, Long groupBuyer) {
        YgGroupBuying groupBuy = this.findById(groupBuyId);
        if (groupBuy.getUserId().equals(groupBuyer)) {
            return this.updateGroupBuyStatus(CompleteStatus.Complete, groupBuyId);
        }
        return 0;
    }

    @Override
    public int updateGroupBuyStatus(CompleteStatus groupBuyStaus, Long groupBuyId) {
        YgGroupBuying ygGroupBuying = new YgGroupBuying();
        ygGroupBuying.setId(groupBuyId);
        ygGroupBuying.setCompleteStatus(groupBuyStaus);
        return this.update(ygGroupBuying);
    }

    @Override
    public List<YgGroupOrderRemindModel> findGroupOrderIncompleteReminder(Date limitTime, Date startTime, Date endTime) {
        return ygGroupBuyingMapper.selectGroupOrderIncompleteReminder(limitTime, startTime, endTime);
    }

    @Override
    public List<YgGroupOrderRemindModel> findGroupBuy4Complete(Date startTime, Date endTime) {
        return ygGroupBuyingMapper.selectGroupBuy4Complete(startTime, endTime);
    }

    @Override
    public int updateGbForCompleteBatch(List<YgGroupBuying> gbList) {
        if (CollectionUtils.isNotEmpty(gbList)) {
            ygGroupBuyingMapper.updateGbForCompleteBatch(gbList);
        }
        return 0;
    }

    @Override
    public int updateGroupBuyAmount(Long id, Long detailAmount, Boolean resetCompleteTime) {
        Date completeTime = null;
        if (resetCompleteTime != null && resetCompleteTime) {
            int randomNum = this.getRandomNum(300, 480);
            completeTime = DateConvertUtils.addMinute(new Date(), randomNum);
        }
        return ygGroupBuyingMapper.updateGroupBuyAmount(id, detailAmount, completeTime);
    }

    @Override
    public ResultSet<YgGroupBuying> search(QueryInfo queryInfo, Long id, String userName, Date startDate, Date endDate, String groupName,
                                           CompleteStatus completeStatus) {
        List<YgGroupBuying> list = ygGroupBuyingMapper.selectSuper(queryInfo, id, userName, startDate, endDate, groupName, completeStatus);

        int count = ygGroupBuyingMapper.countSuper(id, userName, startDate, endDate, groupName, completeStatus);
        ResultSet<YgGroupBuying> resultSet = new ResultSet<YgGroupBuying>(count, list);
        return resultSet;
    }

    @Override
    public List<Long> getNewCustomGroupBuy(String key) {
        String rediskey = "New_Custom_Group_%s";
        String idsStr = redisDao.get(String.format(rediskey, key));
        List<Long> ids = null;
        if (StringUtils.isNotBlank(idsStr)) {
            Long[] idsArr = (Long[]) ConvertUtils.convert(idsStr.split(","), Long.class);
            ids = Arrays.asList(idsArr);
        }
        return ids;
    }

    @Override
    public Message checkNewCustomGroup(List<YgPtSkuInfo> skuList, Boolean isNew, BigDecimal accountPrice) {
        List<Long> newCusSkuIds = this.getNewCustomGroupBuy("Sku");
        for (YgPtSkuInfo sku : skuList) {
            if (newCusSkuIds != null && newCusSkuIds.contains(sku.getSkuId())) {
                if (accountPrice.compareTo(new BigDecimal("0.00")) > 0) {
                    return Message.error("亲，该拼团不允许使用成长基金", null);
                }
                if (!isNew) {
                    return Message.error("亲，该拼团只限新客用户", null);
                }
                if (sku.getQuantity().compareTo(1L) > 0) {
                    return Message.error("不要贪心哦，一个用户只能买一件。", null);

                }
            }
        }
        return Message.success(null);
    }

    @Override
    public List<Long> findSkuIdsByPids(Long[] pIds) {

        return ygGroupBuyingMapper.selectSkuIdsByPids(pIds);
    }

    @Override
    public int updateGbForExpireBatch(List<YgGroupBuying> gbList) {
        if (CollectionUtils.isEmpty(gbList)) {
            return 0;
        }
        return ygGroupBuyingMapper.updateGbForExpireBatch(gbList);
    }

    @Override
    public List<Map<String, Object>> findTuanMemberList(Long groupBuyId) {
        List<Map<String, Object>> list = ygGroupBuyingMapper.selectTuanMemberList(groupBuyId);
        for (Map<String, Object> map : list) {
            Long headUserId = (Long) map.get("headUserId");
            Long memberUserId = (Long) map.get("memberUserId");
            if (headUserId.longValue() == memberUserId.longValue()) {
                map.put("isGroupHead", true);
            } else {
                map.put("isGroupHead", false);
            }
        }
        return list;
    }

    @Override
    public int updateGroupBuyAmountByGroupId(Long groupId, Long groupAmount) {
        if (groupAmount == null || groupAmount == 0) {
            return 0;
        }
        YgGroupBuyingExample example = new YgGroupBuyingExample();
        example.createCriteria().andGroupIdEqualTo(groupId);

        YgGroupBuying groupBuying = new YgGroupBuying();
        groupBuying.setGroupId(groupId);
        groupBuying.setGroupAmount(groupAmount);
        return ygGroupBuyingMapper.updateByExampleSelective(groupBuying, example);
    }
}
